package com.itcast.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author : itheima
 * @date : 2023/6/6 16:48
 * @description :
 */
//@Component
//@Order(-1)
//public class AuthorFilter implements Ordered {
//    @Override
//    public int getOrder() {
//        return -1;
//    }
//}
public class AuthorFilter implements GlobalFilter {

    /**
     * 模拟鉴权
     * @param exchange 封装请求响应向下文信息，包含request response对象等
     * @param chain 全局过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        List<String> token = exchange.getRequest().getHeaders().get("token");
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> map = request.getQueryParams();
        String admin = map.getFirst("authorization");
        if ("admin".equals(admin)) {
            Mono<Void> mn = chain.filter(exchange);//发行请求都下一个过滤器
            return mn;
        }
        //不满足则拦截请求
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.FORBIDDEN);
        Mono<Void> m = response.setComplete();
        return m;
    }
}
